﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ccit.Utils;
using Newtonsoft.Json;

using Ccit.OA.Utils;

namespace Ccit.OA.Scheduler
{
    public partial class scheduler_mySch_edit : Ccit.Utils.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                ViewState["SchId"] = (null != Request.QueryString["SchId"]) ? Request.QueryString["SchId"].ToString() : "";
                ViewState["sUserId"] = (null != Request.QueryString["sUserId"]) ? Request.QueryString["sUserId"].ToString() : "";
                btnSave.Attributes.Add("onclick", "return doSave()");
                btnCancel.Attributes.Add("onclick", "return doSave()");
                tbtqdate.Attributes.Add("onchange", "return IsNumeric()");
                cb_qtsj.Attributes.Add("onclick", "doALLDayClick()");   //全天事件
                initPage();
            }
        }

        public void initPage()
        {
            string sWhere, sId, sUserId;
            sId = ViewState["SchId"].ToString().Trim();
            LoginUser loginUser = Session["LogUserInfo"] as LoginUser;
            sUserId = ViewState["sUserId"].ToString().Trim();

            SchedulerBLL bll = new SchedulerBLL();
            //泛型数组对象用Linq语法进行过滤
            
            if (sUserId == "")
            {
                sUserId = loginUser.UserId;
            }

            #region 初始化数据
            CtrInterface.BindDropDown(ref ddschtype, "bas_a1", "bas_a1_30", "bas_a1_40", false, "", "bas_a1_20='993'");
            CtrInterface.BindDropDown(ref ddrydszt, "bas_a1", "bas_a1_30", "bas_a1_40", false, "", "bas_a1_20='994'");

            ddlrxz.Items.Clear();

            sWhere = " and SCH_A2_20 =" + sUserId;
            DataSet dSet = bll.GetSchProxyMes(sWhere);
            ddlrxz.Items.Add(new ListItem("  ", "0"));
            if (dSet.Tables[0].Rows.Count != 0)
            {
                for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
                {
                    ddlrxz.Items.Add(new ListItem(dSet.Tables[0].Rows[i]["userName"].ToString().Trim(), dSet.Tables[0].Rows[i]["userId"].ToString().Trim()));
                }
            }
            stada.Value = System.DateTime.Now.ToString("yyyy-MM-dd");
            endda.Value = System.DateTime.Now.ToString("yyyy-MM-dd");
            staTime.Value = "00:00";
            endTime.Value = "23:59";

            CJYH.Attributes.Add("style", "display:none");
            #endregion
            if (sId == "")
            {
                #region 当接收到的日程ID为空值时
                txtCreateTime.Text = System.DateTime.Now.ToString().Trim();
                #endregion
            }
            else
            {
                #region 当接收到的日程ID不为空值的时候
                MsScheduler Ms = bll.GetSchedulers("").Where(s => s.SchId == sId.Trim()).ToList<MsScheduler>()[0];
                sWhere = " and sch_a2_10=" + Ms.cjuserId + " and sch_a2_20=" + Ms.ProxyId;
                //给form表单中的控件赋值
                txtCreateTime.Text = Ms.cjdatetime;
                ddschtype.SelectedValue = Ms.SchType;
                ddrydszt.SelectedValue = Ms.State;
                WCBZ.SelectedValue = Ms.CompState;

                txtaddrass.Value = Ms.Location;
                hidCarId.Value = Ms.CarId;  //唯一序列号
                
                RCBT.Value = Ms.Subject;
                //cb_srrc
                if (Ms.SchAttr == "1")
                {
                    cb_srrc.Checked = true;
                }

                if (Ms.SchFlag == "0")
                {
                    rdgrrc.Checked = true;  //个人日程
                    CJYH.Attributes.Add("style", "display:none");
                    doSel("");
                }
                else {
                    #region 编辑/浏览  当ViewState["sUserId"] 不为空时为浏览
                    DataSet dSetProxyMes = bll.GetSchProxyMes(sWhere);
                    if (dSetProxyMes.Tables[0].Rows.Count != 0)
                    {
                        //创建人是自己并且存在代理人
                        if (sUserId == Ms.cjuserId && Ms.ProxyId != "0")
                        {
                            tddlr.InnerHtml = "创建人 ";
                            CJYH.InnerHtml = Ccit.OA.Utils.SysInterface.GetNameStrByIdStr(Ms.ProxyId, NameType.USER, "");
                            doSel(dSetProxyMes.Tables[0].Rows[0]["modifyFlag"].ToString().Trim());
                        }
                        //当前人代理他人设置的日程
                        else if (sUserId != Ms.cjuserId && sUserId == Ms.ProxyId)
                        {
                            tddlr.InnerHtml = "被代理人";
                            doSel("1");
                        }
                        else
                        {
                            tddlr.InnerHtml = "请选择代理人";
                        }
                    }
                    else
                    {
                        doSel("");
                        tddlr.InnerHtml = "请选择代理人";
                    }
                    #endregion
                    rddlrc.Checked = true;
                    ddlrxz.SelectedValue = Ms.cjuserId;
                    CJYH.Attributes.Add("style", "display:block");
                }
                stada.Value = Ms.BeginTime.Split(' ')[0].Trim();
                endda.Value = Ms.EndTime.Split(' ')[0].Trim();
                staTime.Value = Ms.BeginTime.Split(' ')[1].Trim();
                endTime.Value = Ms.EndTime.Split(' ')[1].Trim();
                if (Ms.AllDay == "1")
                {
                    cb_qtsj.Checked = true;
                    tr3.Attributes.Add("style", "display:none");
                }

                tr1.Attributes.Add("style", "display:none");
                for (int i=0; i < Ms.RemindType.Length; i++)
                {
                    if (Ms.RemindType[i].ToString().Trim() != "0")
                    {
                        cb_txfs.Items[i].Selected = true;
                    }
                }
                tbtqdate.Text = Ms.AdvTime;
                ddtqdatetype.SelectedValue = Ms.RemindTimeType;
                RCNR.Value = Ms.schConvert;
                #endregion

                Ms = null;
            }

            bll = null;
            loginUser = null;
           
        }

        public void doSel(string smodifysFlag)
        { 
            string sUserId;
            sUserId = ViewState["sUserId"].ToString().Trim();
            if (sUserId != "" || smodifysFlag == "0")
            {
                cb_qtsj.Enabled = false;
                cb_srrc.Enabled = false;
                cb_txfs.Enabled = false;
                ddlrxz.Enabled = false;
                ddrydszt.Enabled = false;
                ddschtype.Enabled = false;
                ddtqdatetype.Enabled = false;
                tbtqdate.Enabled = false;
                RCBT.Attributes.Add("readonly", "readonly");
                RCNR.Attributes.Add("readonly", "readonly");
                RCLB.Attributes.Add("readonly", "readonly");
                rddlrc.Attributes.Add("readonly", "readonly");
                rdgrrc.Attributes.Add("readonly", "readonly");
                txtaddrass.Attributes.Add("readonly", "readonly");
                txtCreateTime.Attributes.Add("readonly", "readonly");
                stada.Attributes.Add("readonly", "readonly");
                endda.Attributes.Add("readonly", "readonly");
                staTime.Attributes.Add("readonly", "readonly");
                endTime.Attributes.Add("readonly", "readonly");
                btnSave.Visible = false;
                btnCancel.Visible = false;
                rddlrc.Attributes.Add("disabled", "false");
                rdgrrc.Attributes.Add("disabled", "false");
                if (WCBZ.Items.Count != 0)
                {
                    for (int i = 0; i < WCBZ.Items.Count; i++)
                    {
                        WCBZ.Items[i].Attributes.Add("disabled", "false");
                    }
                }
            }

        }

        public bool doSave()
        {
            string sSchId;
            bool bFlag = false;
            sSchId = ViewState["SchId"].ToString().Trim();
            LoginUser loginUser = (LoginUser)HttpContext.Current.Session["LogUserInfo"];
            MsScheduler Ms = new MsScheduler();

            if (sSchId == "")
            {
                Ms.CarId = hidCarId.Value =System.Guid.NewGuid().ToString();
            }
            else {
                Ms.SchId = sSchId;
                Ms.CarId = hidCarId.Value;
            }
            //个人日程
            if (rdgrrc.Checked == true)
            {
                Ms.ProxyId = "";
                Ms.SchFlag = "0";
                Ms.cjuserId = loginUser.UserId;
            }
            else {  //代理日程
                if (ddlrxz.SelectedValue == "")
                {
                    Ms.ProxyId = "0";
                }
                else {
                    Ms.cjuserId = ddlrxz.SelectedValue;
                    Ms.ProxyId = loginUser.UserId;
                }
                Ms.SchFlag = "1";
                rddlrc.Checked = true;
                rdgrrc.Checked = false;
            }
            Ms.Subject = RCBT.Value.Trim();     //标题
            Ms.Location = txtaddrass.Value.Trim();  //地址
            Ms.BeginTime = stada.Value.Trim().Split(' ')[0] + " " + staTime.Value.Trim(); ;      //开始时间
            Ms.EndTime = endda.Value.Trim().Split(' ')[0] + " " +endTime.Value.Trim();        //结束时间

            if (cb_qtsj.Checked == true)             //全天事件
            {
                Ms.AllDay = "1";
                staTime.Value = "00:00";
                endTime.Value = "23:59";
            }
            else
            {
                Ms.AllDay = "0";
            }

            Ms.SchType = ddschtype.SelectedValue.Trim();    //日程类型
            Ms.State = ddrydszt.SelectedValue.Trim();  //人员当时状态

            if (cb_srrc.Checked == true)                    //日程性质（0：普通日程，1：私人日程）
                Ms.SchAttr = "1";
            else
                Ms.SchAttr = "0";

            Ms.CompState = WCBZ.SelectedValue.Trim();   //完成标志

            string stxfs = "";                              
            for (int i = 0; i < cb_txfs.Items.Count; i++)
            {
                if (cb_txfs.Items[i].Selected == true)
                {
                    stxfs += cb_txfs.Items[i].Value;
                }
                else {
                    stxfs += "0";
                }
            }
            Ms.RemindType = stxfs;                                   //提醒方式
            Ms.AdvTime = tbtqdate.Text.Trim();                       //提前提醒时间
            Ms.RemindTimeType = ddtqdatetype.SelectedValue;          //提前提醒时间类型
            Ms.schConvert = RCNR.Value.Trim();
           
            Ms.jobId = loginUser.PosId;
            Ms.levelId = loginUser.ClassId;
            Ms.deptId = loginUser.DeptId;
            Ms.agencId = loginUser.OrganId;
            Ms.cjdatetime = txtCreateTime.Text.Trim();

            SchedulerBLL bll = new SchedulerBLL();
            if (sSchId == "")
            {
                if (Ms.BeginTime != Ms.EndTime)
                {
                    int Day = Convert.ToDateTime(Ms.EndTime).Day - Convert.ToDateTime(Ms.BeginTime).Day;
                    for (int i = 0; i <= Day; i++)
                    {
                        Ms.SchId = DataInterface.GetMaxId("SCH_A1", "SCH_A1_10").ToString();
                        Ms.BeginTime = Convert.ToDateTime(stada.Value.Trim()).AddDays(i).ToString("yyyy-MM-dd") + " " + staTime.Value.Trim();
                        Ms.EndTime = Convert.ToDateTime(Ms.BeginTime).ToString("yyyy-MM-dd") + " " + endTime.Value.Trim();

                        bFlag = bll.AddScheduler(Ms);
                        bll.SendMessage(Ms);
                    }
                }
            }
            else {
                bFlag = bll.UpdateSch(Ms);
            }
            bll = null;
            Ms = null;
            return bFlag;
            
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string sSchId, sMessage = "日程添加失败,请与管理员联系！";
            sSchId = ViewState["SchId"].ToString().Trim();
            if (doSave() == true)
            {
                if (sSchId == "")
                {
                    sMessage = "日程添加成功！";
                }
                else
                {
                    sMessage = "日程更新成功！";
                }
                Response.Write("<script>alert('" + sMessage + "');</script>");
            }
            else
            {
                Response.Write("<script>alert('" + sMessage + "')</script>");
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string sSchId, sMessage = "日程添加失败,请与管理员联系！";
            sSchId = ViewState["SchId"].ToString().Trim();
            if (doSave() == true)
            {
                if (sSchId == "")
                {
                    sMessage = "日程添加成功！";
                }
                else
                {
                    sMessage = "日程更新成功！";
                }
                Response.Write("<script>alert('" + sMessage + "');window.location.href='./scheduler_mySch_frame.aspx';</script>");
            }
            else
            {
                Response.Write("<script>alert('" + sMessage + "')</script>");
            }
        }

        protected void btnback_Click(object sender, EventArgs e)
        {
            Response.Redirect("./scheduler_mySch_frame.aspx");
        }



    }
}
